<template>
  <div class="v-attr-compounded-input">
    <a-select v-model="localType" size="small" style="width: 70px; float: left" @change="handleTypeChange">
      <a-select-option       
        v-for=" (item,index) in valuetypes"
        :key="index"
        :value="item.value"
        :title="item.label"
      >
        {{item.label}}
      </a-select-option>
    </a-select>
    <div style="font-size:12px; overflow: hidden; height: 24px">
      <a-input
        v-if="selectedType.type==='input'"
        v-model="localValue"
        style="font-size:12px"
        :disabled="selectedType.disabled"
        size="small"
        @blur="handleInputChange"/>

      <a-checkbox
        v-else-if="selectedType.type==='switch'"
        size="small"
        :checked="!!localValue"
        :disabled="selectedType.disabled"
        style="font-size:12px"
        @change="handleCheckChange($event,row)">
        {{ !!localValue }}
      </a-checkbox>

      <span v-else-if="selectedType.type==='code'">
        {{localValue}}
        <span v-if="!selectedType.disabled" class="_img-btn" style="position:absolute;top:8px;right:4px" @click.stop="handleEditCode(row)">
          <img style="height:12px;width:12px" src='statics/icons/app/iconmore.png'>
        </span>
      </span>

      <span
        v-else-if="selectedType.type==='tree-single-select'"
        style="display: inline-block; width: 100%; padding: 0 25px 0 10px;text-overflow: ellipsis;white-space: nowrap;overflow: hidden;">
        <a-select
          v-if="showSelect"
          v-model="defaultEnumeration"
          size="small"
          style="width: 100%;"
          @change="handleEnumerationChange">
          <a-select-option
            v-for="(item, index) in enumerations"
            :key="item.id"
            :value="index"
            :title="item.name"
          >
            {{item.name}}
          </a-select-option>
        </a-select>
        <span v-if="!showSelect">{{getName()}}</span>
        <span v-if="!selectedType.disabled" class="_img-btn" style="position:absolute;top:8px;right:4px" @click.stop="handleSingleSelect(row)">
          <img style="height:12px;width:12px" src='statics/icons/app/iconmore.png'>
        </span>
      </span>
    </div>
  </div>
</template>
<script>
import { SysMLUtilHelper } from 'src/api/sysml-imports';

import { selectValue } from '../modals/SelectValue';
import { editCode } from '../modals/EditCode';
import { valuetypes } from '../config/index';
import { PropertyUtil } from './PropertyUtil';
export default {
  name: 'comp-',
  components: {
  },
  props: {
    type: String,
    value: [Object],
    row: Object,
  },
  data() {
    return {
      valuetypes,
      localValue: null,
      localType: this.type,
      currentValue: {},
      showSelect: false,
      enumerations: [],
      defaultEnumeration: ''
    };
  },
  computed: {
    selectedType(){
      return  this.valuetypes.find(item => item.value === this.localType);
    },
  },
  watch: {
    row() {
      console.log('row change');
      this.resetCurrentValue();
    },
    type(val){
      console.log('type更新了！！！！！！！！！！！');
      this.localType = val;
      this.isEnumeration();
    },
    value(val){
      console.log('value更新了！！！！！！！！！！！');
      this.isEnumeration();
    },
    //// value(val){
    ////   console.log('value', val, this.localType);
    //// if (this.selectedType.type === "input" || this.selectedType.type === "switch") {
    ////   this.currentValue[this.localType] = SysMLUtilHelper.getValueSpecificationValue(val);
    //// } else {
    ////   this.currentValue[this.localType] = val;
    //// }
    //// this.localValue = this.currentValue[this.localType];
      
    //// }
  },
  created () {
    this.resetCurrentValue();
  },
  methods: {
    //// 切换元素后重置
    resetCurrentValue () {
      this.showSelect = false;
      this.currentValue = {};
      this.localType = this.type;
      this.localValue = this.currentValue[this.type] = this.getValue(this.value);
      console.log('this.selectedType.type', this.selectedType.type, this.localValue);
      if (this.localType === 'LiteralNull') {
        this.localValue = this.currentValue[this.localType] = '';
      } else if (this.selectedType.type === "input" || this.selectedType.type === "switch" || this.selectedType.type === "code") {
        this.currentValue[this.localType] = SysMLUtilHelper.getValueSpecificationValue(this.value);
        this.localValue = this.currentValue[this.localType];
        console.log('localValue', this.localValue);
      }
      if (this.localType === "LiteralUnlimitedNatural") {
        if (this.localValue < 0) {
          this.localValue = this.currentValue[this.localType] = '*';
        }
      }
      this.isEnumeration();
    },

    //// 如果关联类型是枚举类型，需特殊处理
    isEnumeration() {
      this.defaultEnumeration = '';
      const linkedType = PropertyUtil.getNodePropertyValue(app.selectedElement, 'Type');
      if (linkedType && linkedType.typeName === 'Enumeration' && app.selectedElement.getTypeName() === 'ValueProperty') {
        console.log('this.value', this.value);
        if (this.value === null || this.localType === 'InstanceValue') {
          this.localType = 'InstanceValue';
          const enumerations = linkedType.ownedLiterals.toArray();
          if (this.value) {
            const defaultEnumeration = enumerations.findIndex(item => item.id === this.value.instance.id);
            if (defaultEnumeration !== -1) {
              this.defaultEnumeration = defaultEnumeration;
            } else {
              this.showSelect = false;
              return false;
            }
          }
          this.showSelect = true;
          this.enumerations = enumerations;
          return true;
        }
      }
      this.showSelect = false;
      return false;
    },

    handleEnumerationChange(index) {
      const enumeration = this.enumerations[index];
      this.emitChange(enumeration);
    },

    getName () {
      //// console.log('getName', this.localValue);
      if (!this.localValue) return '';
      if (this.localType === 'InstanceValue' || this.localType === 'ElementValue') {
        if (this.localValue.typeName === 'InstanceValue') {
          return this.localValue.instance ? this.localValue.instance.name : '';
        }
        if (this.localValue.typeName === 'ElementValue') {
          return this.localValue.element ? this.localValue.element.name : '';
        }
        return this.localValue ? this.localValue.name : '';
      }
      return '';
    },

    handleTypeChange(val){
      this.localValue = '';
      const selectedType = this.valuetypes.find(item => item.value === val);
      if (this.selectedType.type === 'tree-single-select'){
        //// if (this.isEnumeration()) return;
        this.showSelect = false;
        this.handleSingleSelect();
      } else {       
        this.emitChange();
      }
    },
    getValue(objValue) {
      if (objValue && SysMLUtilHelper.isLiteral(objValue)) {
        return objValue.value;
      } else {
        return objValue;
      }
    },
    handleCheckChange(e){
			 this.localValue = e.target.checked;
			 this.emitChange();

    },
    emitChange(val){
      let value = val || this.localValue;
      let type = this.localType;
      let newValue;
      if (type === "OpaqueExpression") {
        if (!value) {
          newValue = SysMLUtilHelper.createValueSpecificationByType(type, '', '');
        } else {
          newValue = SysMLUtilHelper.createValueSpecificationByType(type, value.codeType, value.value);
        }       
      } else if (type === 'ElementValue' || type === 'InstanceValue') {
        newValue = SysMLUtilHelper.createValueSpecificationByType(type, value);
      } else {
        newValue = SysMLUtilHelper.createValueSpecificationByType(type, value + "");
      }
      this.$emit('change', newValue);
      this.updateValue(value);
    },
    handleSingleSelect(){
      if (this.inSelect) return;
      this.inSelect = true;
      let filterCondtion = this.row.config.moreBtnCondition;
      if (this.selectedType.value === 'ElementValue') {
        filterCondtion = 'UML Standard Profile::UML2 Metamodel::Element';
      } else if (this.selectedType.value === 'InstanceValue') {
        filterCondtion = 'UML Standard Profile::UML2 Metamodel::InstanceSpecification';
      }
      console.log('this.row.config', filterCondtion, this.row.config);
      selectValue.popup({
        currentId: this.localValue?.element?.id,
        filterCondtion: filterCondtion,
        propertyKey: this.row.config.key
      }).then(res => {
        this.emitChange(res.graphNode.model);
        //// this.updateRow(row, res.model);

      }).catch(e => {
        e && console.error(e);
      }).finally(res => {
        this.inSelect = false;
      });

    },

    handleInputChange() {
      const value = this.selectedType.value;
      if (value === 'LiteralInteger') {
        if (isNaN(this.localValue) || this.localValue % 1 !== 0) {
          this.$messageBox.error({ id: 100, text: '需要一个整数' });
          return;
        }
      }

      if (value === 'LiteralReal') {
        if (isNaN(this.localValue)) {
          this.$messageBox.error({ id: 100, text: '需要一个数字' });
          return;
        }
      }

      if (value === 'LiteralUnlimitedNatural') {
        if (isNaN(this.localValue) && this.localValue !== '*') {
          this.$messageBox.error({ id: 100, text: '需要一个数字' });
          return;
        }
      }

      if (value === 'LiteralString') {
        if (this.localValue == null) {
          this.localValue = "";
        }
      }
      this.emitChange();
    },
    handleEditCode(){
      editCode.popup({
        codeType: this.row.curType || 'english',
        value: this.localValue || ''
      }).then(res => {
        console.log('res', res);
        //// this.localValue = res;
        this.emitChange(res);
      }).catch(err => console.log(err));
    },

    updateValue(value) {
      console.log('value', this.localType, this.currentValue, value);
      if (this.localType === "OpaqueExpression") {
        this.localValue = this.currentValue[this.localType] = value ? value.value : '';
      } else {
        this.localValue = this.currentValue[this.localType] = value;
      }
      if (this.localType === "LiteralUnlimitedNatural") {
        if (value < 0) {
          this.localValue = this.currentValue[this.localType] = '*';
        }
      }
    }
  }
};
</script>
<style lang="scss">
.v-attr-compounded-input {

	._img-btn {
		padding: 2px;
		display: inline-block;
		box-sizing: border-box;
		cursor: pointer;
		img {
			display: block;
			height: 14px;
			width: 14px;
		}
		&:hover {
			padding: 1px;
			background: #f4df99;
			border: 1px solid #c2b597;
		}
		&:active {
			padding: 1px;
			background: #eac266;
			border: 1px solid #c2b597;
		}
	}

}
</style>
